package com.home.fansea.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.home.fansea.config.FileUploadConfig;
import com.home.fansea.config.MinioConfig;
import com.home.fansea.enums.EnumFileService;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class MinioClientUtils {
    @Autowired
    private MinioConfig minioConfig;

    private volatile static MinioClient minioClient;
    @Autowired
    private FileUploadConfig fileUploadConfig;

    //直接访问桶的存储策略
    public static String BUCKET_POLICY_PUBLIC="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::{}\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::{}/*\"]}]}";


    /**
     * 获取minio客户端实例
     *
     * @return {@link MinioClient}
     */
    @PostConstruct
    public MinioClient getMinioClient() {
        if (!isMinioFileService()) {
            log.error("minio服务未配置");
            return null;
        }
        if (minioClient == null) {
            synchronized (MinioClientUtils.class) {
                if (minioClient == null) {
                    minioClient = MinioClient.builder()
                            .endpoint(minioConfig.getEndpoint())
                            .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                            .build();
                    log.debug("minio文件服务连接成功");
                }
            }
        }
        //初始化默认桶
        if (!bucketExists(minioConfig.getBucketName())) {
            makeBucket(minioConfig.getBucketName());
        }
        return minioClient;
    }

    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     *
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());

            String policyCfg=StringUtils.format(BUCKET_POLICY_PUBLIC,bucketName,bucketName);
            setBucketPolicy(policyCfg,bucketName);
            log.debug("minio文件服务bucketName={}创建成功", bucketName);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return buckets;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        String fileName = IdUtil.getSnowflakeNextIdStr() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传文件路径
        String objectName = DateUtils.datePath() + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 文件上传
     *
     * @param fileName 文件
     * @return Boolean
     */
    public String upload(String fileName) {
        //上传文件路径
        String objectName = FileUtil.getName(fileName);
        try {
            //直接用文件，不需要转
            UploadObjectArgs objectArgs = UploadObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName)
                    .filename(fileName).contentType(getContentType(objectName)).build();
            //文件名称相同会覆盖
            minioClient.uploadObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 文件上传
     *
     * @param bytes     文件数组
     * @param extension 扩展名
     * @return Boolean
     */
    public String upload(byte[] bytes, String extension) {
        //上传文件路径和文件名
        String objectName = IdUtil.getSnowflakeNextIdStr() + "." + extension;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName)
                    .stream(new ByteArrayInputStream(bytes), bytes.length, -1).contentType(getContentType(objectName)).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 预览图片
     *
     * @param fileName
     * @return
     */
    public String preview(String fileName) {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        fileName=getFileName(fileName);
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minioConfig.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                while ((len = response.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     *
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(minioConfig.getBucketName()).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    /**
     * 删除
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName) {
        try {
            fileName=getFileName(fileName);
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build();
            minioClient.removeObject(removeObjectArgs);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    /**
     * 查看桶策略
     * @param bucketName
     * @return
     */
    @SneakyThrows(Exception.class)
    public static String getBucketPolicy(String bucketName) {
        String bucketPolicy = minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket(bucketName).build());
        log.debug(bucketPolicy);
        return bucketPolicy;
    }

    /**
     * 设置桶策略
     * @param policyCfg 策略json
     * @param bucketName 桶名称
     */
    @SneakyThrows(Exception.class)
    public static void setBucketPolicy(String  policyCfg, String bucketName) {
        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policyCfg).build());
    }


    /**
     * 获取文件真实路径
     *
     * @param objectName 文件名
     * @return 文件URL
     */
    public String getResAccessUrl(String  objectName) {
        String fileUrl = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + objectName;
        return fileUrl;
    }
    /**
     * 根据文件名称得到contentType
     *
     * @param objectName
     * @return
     */
    private static String getContentType(String objectName) {
        String contentType = MediaTypeFactory.getMediaType(objectName).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
        return contentType;
    }
    /**
     * 根据文件名URL称得到fileName文件名称，不含路径
     *
     * @param fileName
     * @return
     */
    private String getFileName(String  fileName){
        //如果不是单个文件名称就返回文件名称
        if(fileName.contains(minioConfig.getBucketName())){
            fileName=FileUtil.getName(fileName);
        }
        return fileName;
    }
    /**
     * 是否是minio文件服务
     *
     * @return
     */
    public boolean isMinioFileService() {
        return Objects.equals(fileUploadConfig.getFileService(), EnumFileService.MINIO.getCode());
    }
}
